package com.hunttown.mes.manage.controller._iot;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.IotAlarmTriggerConditionManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.IotAlarmTriggerConditionDTO;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.AlarmMethodEnum;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.TriggerLevelEnum;
import com.hunttown.mes.rpc.domain.enums.iot.alarm.TriggerTypeEnum;
import com.hunttown.mes.rpc.domain.query.IotAlarmTriggerConditionDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.IpUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.common.utils.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2021-03-04 19:17:11
 */
@Controller
@RequestMapping(value = "/iot/alarm-config")
public class AlarmTriggerConditionController {

    private final static Logger logger = LoggerFactory.getLogger(AlarmTriggerConditionController.class);

    private final IotAlarmTriggerConditionManageService iotAlarmTriggerConditionService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;
    private final TransportOperateLogManageService logService;

    @Autowired
    public AlarmTriggerConditionController(IotAlarmTriggerConditionManageService iotAlarmTriggerConditionService, AnalysisManageManageService manageService, ModelService modelService, TransportOperateLogManageService logService) {
        this.iotAlarmTriggerConditionService = iotAlarmTriggerConditionService;
        this.manageService = manageService;
        this.modelService = modelService;
        this.logService = logService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, IotAlarmTriggerConditionDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<IotAlarmTriggerConditionDTO> dataPage = iotAlarmTriggerConditionService.getForPage(dtoQuery);

        for (IotAlarmTriggerConditionDTO item : dataPage.getItems()) {
            item.setTriggerTypeName(TriggerTypeEnum.getEnumByKey(item.getTriggerType()));
            item.setTriggerLevelName(TriggerLevelEnum.getEnumByKey(item.getTriggerLevel()));
            item.setAlarmMethodName(AlarmMethodEnum.getEnumByKey(item.getAlarmMethod()));
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "iot/alarm-config/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        IotAlarmTriggerConditionDTO obj;

        if (id > 0) {
            obj = iotAlarmTriggerConditionService.getById(id);
        } else {
            obj = new IotAlarmTriggerConditionDTO();
            obj.setId(0);
            obj.setIsOpen(1);
            obj.setAlarmFrequency(1440);
        }
        model.addAttribute("Obj", obj);

        //设备
        model.addAttribute("triggerTypeList", TriggerTypeEnum.getEnumList());
        model.addAttribute("triggerLevelList", TriggerLevelEnum.getEnumList());
        model.addAttribute("alarmMethodList", AlarmMethodEnum.getEnumList());

        return "iot/alarm-config/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, IotAlarmTriggerConditionDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (objDTO.getIsNoticeCharge() == null) {
                objDTO.setIsNoticeCharge(0);
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = iotAlarmTriggerConditionService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = iotAlarmTriggerConditionService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 147, objDTO.getId(), 2,
                    "更新报警触发条件",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return josn
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(HttpServletRequest request, Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = iotAlarmTriggerConditionService.delete(id);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 147, id, 4,
                    "删除报警触发条件",
                    "记录删除：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        IotAlarmTriggerConditionDTO obj = new IotAlarmTriggerConditionDTO();
        obj.setId(id);

        if (id > 0) {
            obj = iotAlarmTriggerConditionService.getById(id);
        }
        iotAlarmTriggerConditionService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

}